<?php

function generateToken(){
	
		srand();
	
	$token = "";

	for ($i = 0; $i <64; $i++) {
	    $token .= dechex(rand(0, 15));
	}

	return $token;
}

	session_start();
	
	//Array to store validation errors
	$errmsg_arr = array();
	
	//Validation error flag
	$errflag = false;

	//Include database connection details
	require_once('db/config.php');

	//Connect to mysql server
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	if(!$link) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: login-form.php");
		exit();
	}

	//Select database
	$db = mysql_select_db(DB_DATABASE);
	if(!$db) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: login-form.php");
		exit();
	}


	//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}
	
	//Sanitize the POST values
	$username = clean($_POST['username']);
	$password = clean($_POST['password']);
	

	//Input Validations
	if($username == '') {
		$errmsg_arr[] = 'Username missing';
		$errflag = true;
	}
	if($password == '') {
		$errmsg_arr[] = 'Password missing';
		$errflag = true;
	}

	//If there are input validations, redirect back to the login form
	if($errflag) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: login-form.php");
		exit();

	}

	//Create query
	$qry="SELECT * FROM users WHERE username='$username' AND password='".md5($_POST['password'])."'";
	$result=mysql_query($qry);

	//Check whether the query was successful or not
	if($result) {
		
		if(mysql_num_rows($result) == 1) {

			//Login Successful
			session_regenerate_id();
			$user = mysql_fetch_assoc($result);    
        
			$_SESSION['SESS_USER_ID'] = $user['id'];
			$_SESSION['SESS_USER_USERNAME'] = $user['username'];
			$_SESSION['SESS_USER_FNAME'] = $user['firstname'];
			$_SESSION['SESS_USER_LNAME'] = $user['lastname'];
        
			$_SESSION['SESS_USER_TOKEN'] = generateToken();
			$_SESSION['SESS_USER_IP'] = $_SERVER['REMOTE_ADDR'];
			$_SESSION['SESS_USER_PORT'] = $_SERVER['REMOTE_PORT'];
		
			//Create INSERT query
		
		    $qry = "INSERT INTO sessions(userid, cookie, token, ip, port) VALUES(
				'".$_SESSION['SESS_USER_ID']."',
				'null',
       			'".$_SESSION['SESS_USER_TOKEN']."',
				'".$_SESSION['SESS_USER_IP']."',
				'".$_SESSION['SESS_USER_PORT']."')";


    		$result = @mysql_query($qry);

		    //Chdeck whether the query was successful or not
		    if(!$result) {
		        die("Query failed : > ".$qry); 
		    }

			//Start session

			session_write_close();
			header("location: /protected/index.php");
			exit();
			
		} else {
			$errmsg_arr[] = 'Email or password is incorrect  :-(';
			$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
			session_write_close();
			header("location: login-form.php");
			exit();	
		}

	} else {

            $errmsg_arr[] = 'Query fail. Please try again.';
			$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
			session_write_close();
			header("location: login-form.php");
			exit();	

	}
	
?>
